<?php 
require_once(ROOT_PATH.'includes/smarty/Smarty.class.php');

function formatUrl($url = '' , $options = array())
{
	return ECRewrite::formatUrl($url , $options);
}	    	

	
class ECDisplay extends Smarty{
	
	function ECDisplay(){
		$this->Smarty();
		$this->template_dir = ROOT_PATH."templates/";
		$this->compile_dir 	= DIR_CACHE."templates_c/";
		$this->cache_dir 	= DIR_CACHE."smarty/";
		ECLib::CheckDir($this->compile_dir);	
		ECLib::CheckDir($this->cache_dir);		
		$this->config_dir 	= DIR_CACHE."configs/";
		$this->cache_ext 	= ".tpl";
		$this->caching 		= false;
		//$this->load_filter('output','trimwhitespace');
		
		//$this->debugging = true;
		$this->register_modifier("formatUrl", "formatUrl"); 		
		$this->register_modifier("number_format", "number_format"); 		
	}
	
    function add($key = '' , $value = '')
    {
        $this->assign($key,$value);
    }
    
    function formatUrl($url = '' , $options = array())
    {
        return ECRewrite::formatUrl($url , $options);
    }	    	
	
    //Chi dung cho module, neu ngoai module dung display()...
    //added by Nova 05.06.08
    //modified by TrungNV 02.10.12
    /**
     * @param string $template : tên template
     * @param bool $return	: false -  output trực tiếp, true - trả về giá trị output
     * @param bool|string $direct_dir_path : lấy thư mục chứa template trực tiếp
     * @param bool|string $source : file html nguồn nằm trong _assets/html
     * @param bool|string $form_name : form name hiện tại
     * @return bool|mixed|string
     */
    function output($template = '', $return=false, $direct_dir_path=false, $source=false, $form_name=false) {
    	if($direct_dir_path){
    		$template_dir = $this->template_dir . $direct_dir_path.'/';
    	}
    	else{
			if(Module::$name!=''){
    			$template_dir = $this->template_dir . Module::$name.'/';
    		}
    		else{
    			$template_dir = $this->template_dir . $template.'/';
    		}
    	}
    	ECLib::CheckDir($template_dir);

        if($source && Url::getInt('render_html_tpl'))
            $this->makeTemplateFileByHtml($template, $template_dir, $source, $form_name);

        $template =   ($template) ? $template_dir.$template . $this->cache_ext 	: "";

    	if($return){
       	 	return $this->fetch($template);
    	}
        else{
        	$this->display($template);
        }
    }	

    //added by TrungNV 02.10.12
    static $_tpl_html = array();

    //added by TrungNV 02.10.12
    private function makeTemplateFileByHtml($template, $template_dir, $source, $form_name=false) {
        $not_exists = false;
        $module_template_file = ($template) ? $template_dir.$template . $this->cache_ext 	: "";
        if(file_exists($module_template_file)) {
            $tpl_file_path = ROOT_PATH. "_assets/html/$source.html";
            if(file_exists($tpl_file_path)) {
                $template_modify_time = filemtime($tpl_file_path);
                $block_modify_time = filemtime($module_template_file);
                if($template_modify_time>$block_modify_time)
                    $not_exists = true;
            }
        } else $not_exists = true;
        if($not_exists) {
            if(!isset($tpl_file_path)) $tpl_file_path = ROOT_PATH. "_assets/html/$source.html";
            if(($html=isset(self::$_tpl_html[$tpl_file_path])) || file_exists($tpl_file_path)) {
                if($html) {
                    $html = self::$_tpl_html[$tpl_file_path];
                } else {
                    $html = file_get_contents($tpl_file_path);
                    self::$_tpl_html[$tpl_file_path] = $html;
                }
                if($form_name) {
                    $form_name = DIR_MODULE. Module::$name. "/forms/$form_name.php";
                    $code = @file_get_contents($form_name);
                    if($code) {
                        $code = explode('/*Auto add assets*/', $code);
                        if(count($code)==3 && preg_match_all("/<(script|link)[^>]*for-module=\"($template|ALL)\"[^>]*>/i", $html, $matches)) {
                            $header = '';
                            if(($k=strpos($code[1], '$'))!==false)
                                $code[1] = substr($code[1], 0, $k);
                            foreach($matches[0] as $k => $pattern) {
                                switch(strtolower($matches[1][$k])) {
                                    case 'link':
                                        if(preg_match('/href="css\/([^"]+)"/i', $pattern, $variable)) {
                                            $this->copyAssetsFile($variable[1], 'css');
                                            $header .= "$code[1]\$this->link_css('style/frontend/$variable[1]');";
                                        }
                                        break;
                                    case 'script':
                                        if(preg_match('/src="js\/([^"]+)"/i', $pattern, $variable)) {
                                            $this->copyAssetsFile($variable[1], 'js');
                                            $header .= "$code[1]\$this->link_js('javascript/frontend/$variable[1]');";
                                        }
                                        break;
                                }
                            }
                            $code[1] = $header. $code[1];
                            $code = implode('/*Auto add assets*/', $code);
                            file_put_contents($form_name, $code);
                        }
                    }
                }
                $html = preg_split("/<!--\[\/?\\$$template\]-->/", $html);
                if(isset($html[1])) {
                    $html = $html[1];
                    $html = preg_replace('/<!--{-->[\d\D]*?<!--}-->/', '', $html);
                    $html = str_replace(array('<!--?php', '?-->', '<!--{', '}-->'), array('<?php', '?>', '{', '}'), $html);
                    if(preg_match_all('/<!--\[([$\w->\[\'"\]]+)\]-->/', $html, $matches)) {
                        $matches = array_unique($matches[1]);
                        foreach($matches as &$variable) {
                            $pattern = preg_quote($variable, '/');
                            $html = preg_replace("/<!--\[$pattern\]-->(([\d\D]*?)<!--\[\/$pattern\]-->)?/", "{{$variable}}", $html);
                        }
                    }
                    if(preg_match_all('/<[^>]*php-var-(\w+)="([^"]*)"[^>]*>/', $html, $matches)) {
                        $html = preg_split('/<[^>]*php-var-\w+="[^"]*"[^>]*>/', $html);
                        foreach($matches[0] as $k => &$pattern) {
                            $html[$k] .= preg_replace(array(
                                    "/ php-var-{$matches[1][$k]}=\"[^\"]*\"/",
                                    "/{$matches[1][$k]}=\"[^\"]*\"/"),
                                array('', "{$matches[1][$k]}=\"{{$matches[2][$k]}}\""),
                                $pattern);
                        }
                        $html = implode($html);
                    }
                    //$html = $header . $html;
                }
                else $html = '';//&$header;
            } else $html = '';//&$header;
            if(!file_exists($template_dir))
                mkdir($template_dir, 777, true);
            file_put_contents($module_template_file, $html);
        }
    }

    //added by TrungNV 02.10.12
    private function copyAssetsFile($file, $type) {
        $dir = ROOT_PATH. ($type=='js'?'javascript':'style'). '/frontend/';
        if(!file_exists($dir))
            mkdir($dir, 777, true);
        $type = ROOT_PATH. "_assets/$type/$file";
        if(file_exists($type))
            return copy($type, $dir.$file);
        else return false;
    }
}
?>